package com.zyp.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        Client client = new Client();
        client.startclient();

    }

    public void startclient(){
        try {
            Socket socket = new Socket("127.0.0.1",21356);
            handlerconn(socket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handlerconn(Socket socket) {
        System.out.println("socket connected");
        try {


            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("{\"name\":\"zhuyupei\"}".getBytes());
            outputStream.flush();
                ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
                byte[] bytes = new byte[1024];
                int len = 0;
//                System.out.println("read stream");
//                len = inputStream.read(bytes);
//                System.out.println(len);
//                while ((len = inputStream.readAllBytes()) != -1) {
//                    System.out.println(new String(bytes,"UTF-8"));
//                    bout.write(bytes, 0, len);
////                    System.out.println(bout.toString("UTF-8"));
//                }

                while (true){
                    // 获取包大小
                    byte[] pskSizebyte = new byte[8];
                    len = inputStream.read(pskSizebyte);
                    int pkgSize =  Integer.parseInt(new String(pskSizebyte,"UTF-8"));
                    System.out.println(pkgSize);
                    int count = 0;
                    while (count < pkgSize){
                        len = inputStream.read(bytes);
                        bout.write(bytes,0,len);
                        bytes = new byte[1024];
                        count += len;
                    }

                    System.out.println(bout.toString("UTF-8"));



                }


//                System.out.println("read end");
//                bytes = null;
//                String result = bout.toString("UTF-8");
//                System.out.println(result);
//                System.out.println("end");
//                bout = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
